var template = `
<div class="list">
    <table v-if="list.length > 0 && Object.keys(showModel).length > 0" border="0" cellspacing="0" cellpadding="5">
        <tr><th v-for="key in Object.keys(showModel)">{{doGetKey(key)}}</th><th v-if="controlSlot">操作</th></tr>
        <tr :class="{green: doSuccess(item)}" v-for="item in list">
            <td v-for="key in Object.keys(showModel)">{{doFormat(item,key)}}</td>
            <td v-if="controlSlot"><slot :item="item"></slot></td>
            
        </tr>
    </table>
    <div class="no-data" v-else>没有数据</div>
</div>
`;

let List = {
    name: 'List',
    components: {},
    template,
    props: {
        list: {
            type: Array,
            default: []
        },
        showModel: {
            type: Object,
            default: {}
        },
        schema: {
            type: String,
            default: ''
        },
    },
    methods: {
        doFormat(item, key) {
            if (this.showModel[key] && this.showModel[key].formatter) {
                if ('date' === this.showModel[key].type) {
                    return new Date(item[key]).fmt(this.showModel[key].formatter);
                } else {
                    return item[key];
                }
            } else if ('text' === this.showModel[key].type) {
                if (this.showModel[key].maxLength && this.showModel[key].maxLength > 0) {
                    let maxLength = this.showModel[key].maxLength;
                    if (typeof (item[key]) === 'string' && item[key].length > maxLength) {
                        return item[key].substr(0, maxLength) + '...';
                    } else {
                        return item[key];
                    }
                } else {
                    return item[key];
                }
            } else {
                return item[key];
            }
        },
        doSuccess(item) {
            let successKeys = Object.keys(this.showModel).filter(key => !!this.showModel[key] && this.showModel[key].hasOwnProperty('success'));
            let success = successKeys.length > 0;
            successKeys.forEach(key => {
                if (item[key] !== this.showModel[key]['success']) {
                    success = false;
                }
            });
            return success;
        },
        doGetKey(key = '') {
            let {apiDocs} = this.sharedState;
            if (apiDocs) {
                let {schemas = {}} = apiDocs.components;
                let schemaObj = schemas[this.schema];
                if (schemaObj) {
                    return schemaObj.properties && schemaObj.properties[key] && schemaObj.properties[key].description || key;
                }
            }
            return key;
        },
    },
    data() {
        const {useSlots} = Vue;
        return {
            sharedState: store.state,
            controlSlot: !!useSlots().default
        }
    }
};